package com.stenio.fancat.controller;

import com.stenio.fancat.common.Constant;
import com.stenio.fancat.common.FanCatException;
import com.stenio.fancat.form.OrderForm;
import com.stenio.fancat.pay.Notice;
import com.stenio.fancat.pay.OrderResult;
import com.stenio.fancat.pay.ReturnMsg;
import com.stenio.fancat.service.PayService;
import com.stenio.fancat.util.RequestUtil;
import com.stenio.fancat.util.ResultUtil;
import com.stenio.fancat.util.XmlUtil;
import com.stenio.fancat.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 支付模块controller
 */
@RestController
@RequestMapping("pay")
public class PayController {

    private final static Logger logger = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private PayService payService;

    @RequestMapping("place-order")
    public Result placeOrder(@RequestBody OrderForm form, HttpServletRequest request) {
        try {
            form.setIp(RequestUtil.getRemoteIp(request));
            OrderResult result = payService.placeOrder(form);
            // 将 prepay_id 返回给客户端
            return Result.success(result);
        } catch (FanCatException e) {
        	logger.error("error",e);
            return ResultUtil.error("1",e.getMessage());
        }

    }

    @RequestMapping("notice")
    public String notice(@RequestBody String xml, HttpServletResponse response) {
        ReturnMsg msg = new ReturnMsg();
        try {
            Notice notice = XmlUtil.toBean(xml, Notice.class);
            payService.processNotice(notice);
            msg.setReturn_code(Constant.SUCCESS);
            msg.setReturn_msg(Constant.OK);
        } catch (IllegalAccessException | InstantiationException | FanCatException e) {
            msg.setReturn_code(Constant.ERROR);
            msg.setReturn_msg(Constant.ERROR);
        }
        return XmlUtil.fromBean(msg);
    }
}
